package com.nova.android.tvlauncher.ui.view

import android.animation.ArgbEvaluator
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Color
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.graphics.drawable.GradientDrawable
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.animation.DecelerateInterpolator
import android.widget.FrameLayout
import androidx.core.content.withStyledAttributes
import com.nova.android.tvlauncher.R
import com.nova.android.tvlauncher.databinding.FocusImageViewBinding

class FocusImageWithTextView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {

    private val binding: FocusImageViewBinding =
        FocusImageViewBinding.inflate(LayoutInflater.from(context), this, true)

    private var focusColor: Int = Color.WHITE
    private var normalColor: Int = Color.TRANSPARENT
    private var scaleFactor: Float = 1.2f
    private var animationDuration: Long = 400
    private var interpolator = DecelerateInterpolator()
    private var backgroundDrawable: GradientDrawable? = null
    private var imageNormalSrc: Drawable? = null
    private var imageFocusSrc: Drawable? = null
    private var focusTextContent: String = ""
    private var focusTextSize: Float = 14f
    private var focusTextColor: Int = Color.WHITE
    private var iconSize: Float = 0f // 新增：ivIcon 默认宽高

    init {
        initAttributes(attrs)
        initViewSettings()
        setupBackground()
        setupText()
        updateFocusState(isFocused, false)
    }

    private fun initAttributes(attrs: AttributeSet?) {
        context.withStyledAttributes(attrs, R.styleable.FocusImageWithTextView) {
            focusColor = getColor(R.styleable.FocusImageWithTextView_fiwt_focus_color, Color.WHITE)
            normalColor = getColor(R.styleable.FocusImageWithTextView_fiwt_normal_color, Color.TRANSPARENT)
            scaleFactor = getFloat(R.styleable.FocusImageWithTextView_fiwt_scale_factor, 1.2f).coerceAtLeast(1.0f)
            animationDuration = getInt(R.styleable.FocusImageWithTextView_fiwt_animation_duration, 400).toLong()
            imageNormalSrc = getDrawable(R.styleable.FocusImageWithTextView_fiwt_normal_src)
            imageFocusSrc = getDrawable(R.styleable.FocusImageWithTextView_fiwt_focus_src)
            focusTextContent = getString(R.styleable.FocusImageWithTextView_fiwt_focus_text_content) ?: ""
            focusTextSize = getDimension(R.styleable.FocusImageWithTextView_fiwt_focus_text_size, 14f)
            focusTextColor = getColor(R.styleable.FocusImageWithTextView_fiwt_focus_text_color, Color.WHITE)
            iconSize = getDimension(R.styleable.FocusImageWithTextView_fiwt_icon_size, 0f) // 新增：读取 iconSize 属性
        }
    }

    private fun initViewSettings() {
        clipChildren = false
        clipToPadding = false
        // 新增：设置 ivIcon 的默认宽高
        if (iconSize > 0) {
            val layoutParams = binding.ivIcon.layoutParams
            layoutParams.width = iconSize.toInt()
            layoutParams.height = iconSize.toInt()
            binding.ivIcon.layoutParams = layoutParams
        }
    }

    private fun setupBackground() {
        backgroundDrawable = GradientDrawable().apply {
            shape = GradientDrawable.OVAL
            setColor(if (isFocused) focusColor else normalColor)
        }
        binding.rlBg.background = backgroundDrawable
    }

    private fun setupText() {
        binding.focusText.apply {
            text = focusTextContent
            textSize = focusTextSize / resources.displayMetrics.scaledDensity // 转换为 sp
            setTextColor(focusTextColor)
            visibility = if (focusTextContent.isEmpty()) GONE else {
                alpha = if (isFocused) 1.0f else 0.0f
                if (isFocused) VISIBLE else INVISIBLE
            }
        }
    }

    override fun onFocusChanged(focused: Boolean, direction: Int, previouslyFocusedRect: Rect?) {
        super.onFocusChanged(focused, direction, previouslyFocusedRect)
        binding.focusText.isSelected = focused
        updateFocusState(focused, true)
    }

    private var lastSetSelectedTime: Long = 0
    private val debounceInterval: Long = 800

    override fun setSelected(selected: Boolean) {
        val currentTime = System.currentTimeMillis()
        if (currentTime - lastSetSelectedTime < debounceInterval) {
            return
        }
        lastSetSelectedTime = currentTime
        super.setSelected(selected)
        updateFocusState(selected, true)
    }

    private fun updateFocusState(focused: Boolean, withAnimation: Boolean) {
        binding.ivIcon.setImageDrawable(if (focused && imageFocusSrc != null) imageFocusSrc else imageNormalSrc)

        if (withAnimation) {
            animateBackgroundColor(focused)
            animateIconScale(focused)
            animateBackgroundScale(focused)
            if (focusTextContent.isNotEmpty()) {
                animateTextVisibility(focused)
            }
        } else {
            backgroundDrawable?.setColor(if (focused) focusColor else normalColor)
            binding.ivIcon.scaleX = if (focused) scaleFactor else 1f
            binding.ivIcon.scaleY = if (focused) scaleFactor else 1f
            binding.rlBg.scaleX = if (focused) scaleFactor else 1f
            binding.rlBg.scaleY = if (focused) scaleFactor else 1f
            if (focusTextContent.isNotEmpty()) {
                binding.focusText.apply {
                    alpha = if (focused) 1.0f else 0.0f
                    visibility = if (focused) VISIBLE else INVISIBLE
                }
            }
        }
    }

    private fun animateBackgroundColor(focused: Boolean) {
        ValueAnimator.ofObject(
            ArgbEvaluator(),
            if (focused) normalColor else focusColor,
            if (focused) focusColor else normalColor
        ).apply {
            duration = animationDuration
            addUpdateListener { animator ->
                backgroundDrawable?.setColor(animator.animatedValue as Int)
            }
            start()
        }
    }

    private fun animateIconScale(focused: Boolean) {
        binding.ivIcon.animate()
            .scaleX(if (focused) scaleFactor else 1f)
            .scaleY(if (focused) scaleFactor else 1f)
            .setDuration(animationDuration)
            .setInterpolator(interpolator)
            .start()
    }

    private fun animateBackgroundScale(focused: Boolean) {
        binding.rlBg.animate()
            .scaleX(if (focused) scaleFactor else 1f)
            .scaleY(if (focused) scaleFactor else 1f)
            .setDuration(animationDuration)
            .setInterpolator(interpolator)
            .start()
    }

    private fun animateTextVisibility(focused: Boolean) {
        if (focusTextContent.isEmpty()) {
            binding.focusText.visibility = GONE
            return
        }
        binding.focusText.animate()
            .alpha(if (focused) 1.0f else 0.0f)
            .setDuration(800)
            .setInterpolator(interpolator)
            .withStartAction {
                if (focused) binding.focusText.visibility = VISIBLE
            }
            .withEndAction {
                if (!focused) binding.focusText.visibility = INVISIBLE
            }
            .start()
    }

    fun setFocusColor(color: Int) {
        focusColor = color
        if (isFocused) backgroundDrawable?.setColor(focusColor)
    }

    fun setNormalColor(color: Int) {
        normalColor = color
        if (!isFocused) backgroundDrawable?.setColor(normalColor)
    }

    fun setScaleFactor(factor: Float) {
        scaleFactor = factor.coerceAtLeast(1.0f)
        if (isFocused) {
            binding.ivIcon.scaleX = scaleFactor
            binding.ivIcon.scaleY = scaleFactor
            binding.rlBg.scaleX = scaleFactor
            binding.rlBg.scaleY = scaleFactor
        }
    }

    fun setAnimationDuration(duration: Long) {
        animationDuration = duration.coerceAtLeast(0)
    }

    fun setInterpolator(customInterpolator: DecelerateInterpolator) {
        interpolator = customInterpolator
    }

    fun setImageNormalSrc(drawable: Drawable?) {
        imageNormalSrc = drawable
        if (!isFocused) binding.ivIcon.setImageDrawable(imageNormalSrc)
    }

    fun setImageFocusSrc(drawable: Drawable?) {
        imageFocusSrc = drawable
        if (isFocused) binding.ivIcon.setImageDrawable(imageFocusSrc)
    }

    fun setFocusTextContent(text: String) {
        focusTextContent = text
        binding.focusText.text = text
        binding.focusText.visibility = if (text.isEmpty()) GONE else {
            if (isFocused) VISIBLE else INVISIBLE
        }
    }

    fun setFocusTextSize(size: Float) {
        focusTextSize = size
        binding.focusText.textSize = size
    }

    fun setFocusTextColor(color: Int) {
        focusTextColor = color
        binding.focusText.setTextColor(color)
    }

    // 新增：设置 iconSize 的方法
    fun setIconSize(size: Float) {
        iconSize = size
        if (size > 0) {
            val layoutParams = binding.ivIcon.layoutParams
            layoutParams.width = size.toInt()
            layoutParams.height = size.toInt()
            binding.ivIcon.layoutParams = layoutParams
        }
    }
}